package com.rtf.framework.web.mvc.config.secure.handler;

import com.rtf.framework.common.config.AppSecureProperties;
import com.rtf.framework.common.util.UtilString;
import com.rtf.framework.web.http.ResponseParam;
import com.rtf.framework.web.util.UtilWeb;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class AppLogoutSuccessHandlerDefault implements LogoutSuccessHandler {

    @Autowired
    private AppSecureProperties appSecureProperties;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.debug("退出成功: {}" , request.getSession().getId()) ;

        // 如果是post请求直接返回json信息
        if (UtilString.equalsIgnoreCase(request.getMethod(), "post")) {
            UtilWeb.writeToResponse(response,
                    ResponseParam.success().message("退出成功")
                            .getResponseEntity(HttpStatus.OK));
        } else {
            // 退出成功如果携带回调地址，重定向到该地址，否则重定向到默认登陆页面
            String redirectUri = request.getParameter("redirect_uri");
            if (UtilString.isBlank(redirectUri)) {
                redirectUri = appSecureProperties.getAuth().getLoginUrl();
            }
            response.sendRedirect(redirectUri);
        }
    }
}
